var app = getApp();
var currentShopId = 0;

Page({
  data: {
    products: [],
    total_amount: 0,
    addrs: [],
    addrId: 0,
    showAddrDialog: false,
    showAddrsDialog: false,
    showAddrEditDialog: false,
    is_express: false
  },
  onLoad: function (options) {
    var that = this;
    //获取店铺id
    currentShopId = wx.getStorageSync('shop_id');
    if (!currentShopId) {
      currentShopId = wx.getStorageSync('current_shop_id')
    };
    //获取店铺信息
    app.func.req('shops/show', {
      id: currentShopId
    }, 'GET', function (res) {
      var shop = res.result
      that.setData({
        shop: shop
      });
      var isthreshold = false;
      var carts = wx.getStorageSync('carts');
      if (options.is_express == 'true') {
        var expressCart = wx.getStorageSync('expressCart');
        that.setData({
          is_express : true
        });
        carts = [expressCart]
      }
      for (var i = 0; i < carts.length; i++) {
        if (carts[i].shopId == currentShopId) {
          var total_amount = carts[i].total;
          var hasDelivery = false;
          var isDeliveryFree = false
          if (!carts[i].is_zan && !carts[i].is_platform) {
            if (total_amount < shop.start_delivery_amount) {
              wx.showModal({
                title: '提示',
                content: '订单未到起送量，建议加入购物车',
                showCancel: false,
                confirmText: '返回商品',
                success: function(res) {
                  wx.navigateBack()
                } 
              })
            }
            if (shop.delivery_free > 0 && total_amount >= shop.delivery_free) {
              isDeliveryFree = true
            } else {
              total_amount = Number(total_amount) + Number(shop.delivery_amount);
            }
            if (shop.is_threshold == '1' && total_amount >= shop.threshold) {
              total_amount = Number(total_amount) - Number(shop.threshold_rebate);
              isthreshold = true;
            }   
            hasDelivery = true;
          }
          var ids = new Array();
          var c = i;
          carts[i].products.forEach(function(item,index,array){
            ids.push(parseInt(item['id']));
          })
          ids = JSON.stringify(ids);
        app.func.req('products/cat', {
          ids: ids,
        }, 'GET', function(r){
          if (r.code == 'success') {
            that.setData({
              isthreshold: isthreshold,
              products: carts[c].products,
              total_amount: Math.round(total_amount * 100) / 100,
              hasDelivery: hasDelivery,
              isDeliveryFree: isDeliveryFree
            });
          }
          if (r.code == 'error'){
              if(r.msg==1){
                  wx.showToast({
                  title: '商品已下架',
                  icon: 'success',
                  duration: 3000
                });
              }
              if(r.msg==2){
                wx.showToast({
                  title: '商品分类已下架',
                  icon: 'success',
                  duration: 3000
                });
              }
              setTimeout(function(){   
                wx.redirectTo({
                  url: "/pages/products/products_flex?shop_id="+currentShopId
              })}, 3000);
          }
        },{
          token: wx.getStorageSync('token')
        });




        }
      }
      //获取收货地址列表
      that.getArea('', '', '');
      //获取默认地址

      that.getAddrs();
    }, {
        'token': wx.getStorageSync('token')
      });
  },
  getArea: function (code1, code2, code3) {
    var that = this;
    //获取省级
    app.func.req('Addresses/areas', {
      code: ''
    }, 'GET', function (res) {
      var provinces = res.result;
      var provincesArray = [];
      var provinceIndex = 0;
      var provinceCode = code1;
      var cityCode = code2;
      var areaCode = code3;
      for (var i = 0; i < provinces.length; i++) {
        provincesArray.push(provinces[i].name);
        if (provinces[i].code == code1) {
          provinceIndex = i;
        }
      }
      if (code1 == '') {
        provinceIndex = 0;
        provinceCode = provinces[0].code;
      }
      //获取市级
      app.func.req('Addresses/areas', {
        code: provinceCode
      }, 'GET', function (res1) {
        var cities = res1.result;
        var citiesArray = [];
        var cityIndex = 0;
        for (var i = 0; i < cities.length; i++) {
          citiesArray.push(cities[i].name);
          if (cities[i].code == code2) {
            cityIndex = i;
          }
        }
        if (code2 == '') {
          cityIndex = 0;
          cityCode = cities[0].code;
        }
        //获取区域
        app.func.req('Addresses/areas', {
          code: cityCode
        }, 'GET', function (res2) {
          var areas = res2.result;
          var areasArray = [];
          var areaIndex = 0;
          for (var i = 0; i < areas.length; i++) {
            areasArray.push(areas[i].name);
            if (areas[i].code == code3) {
              areaIndex = i;
            }
          }
          if (code3 == '') {
            areaIndex = 0;
            areaCode = cities[0].code;
          }
          that.setData({
            provinces: provinces,
            provincesArray: provincesArray,
            provinceIndex: provinceIndex,
            cities: cities,
            citiesArray: citiesArray,
            cityIndex: cityIndex,
            areas: areas,
            areasArray: areasArray,
            areaIndex: areaIndex
          })
        }, {
            'token': wx.getStorageSync('token')
          })
      }, {
          'token': wx.getStorageSync('token')
        })

    }, {
        'token': wx.getStorageSync('token')
      })
  },
  newAddr: function () {
    this.setData({
      showAddrDialog: true,
      showAddrsDialog: false
    })
  },
  closeAddrDialog: function () {
    this.setData({
      showAddrDialog: false
    })
  },
  closeAddrsDialog: function () {
    this.setData({
      showAddrsDialog: false
    })
  },
  closeAddrEditDialog: function () {
    this.setData({
      showAddrEditDialog: false,
      showAddrsDialog: true
    })
  },
  bindProvinceChange: function (e) {
    var code = this.data.provinces[e.detail.value].code;
    this.getArea(code, '', '');
  },
  bindCityChange: function (e) {
    var code1 = this.data.provinces[this.data.provinceIndex].code;
    var code2 = this.data.cities[e.detail.value].code;
    this.getArea(code1, code2, '');
  },
  bindAreaChange: function (e) {
    this.setData({
      areaIndex: e.detail.value
    })
  },
  getAddrs: function () {
    var that = this;
    var addrId = wx.getStorageSync('addrId');
    var curAddr = null
    app.func.req('Addresses/index', {}, 'GET', function (res) {
      that.setData({
        addrs: res.result
      })
   if(res.result && res.result!='')
   {
      wx.setStorage({
        key: 'addrId',
        data: res.result[0].id
      })
   }else{
    return;
   }
      if (addrId >= 0) {
        for (var i = 0; i < res.result.length; i++) {
          if (res.result[i].id == addrId) {
            curAddr = res.result[i]
          }
        }
      }

      if (!curAddr) {
        curAddr = res.result[0],
          addrId = res.result[0].id
      }
      that.setData({
        curAddr: curAddr,
        addrId: addrId
      })
    }, {
        'token': wx.getStorageSync('token')
      })
  },
  selectAddr: function (e) {
    var index = e.currentTarget.dataset.index;
    var curAddr = this.data.addrs[index];
    this.setData({
      curAddr: curAddr,
      addrId: curAddr.id,
      showAddrsDialog: false
    })
    wx.setStorage({
      key: 'addrId',
      data: curAddr.id
    })
  },
  createAddr: function (e) {
    console.log(e);
    var that = this;
    var province_code = that.data.provinces[e.detail.value.province].code;
    var city_code = that.data.cities[e.detail.value.city].code;
    var area_code = that.data.areas[e.detail.value.area].code;
    var addr = e.detail.value.detail;
    var receiver_name = e.detail.value.name;
    var receiver_mobile = e.detail.value.phone;
    console.log(city_code);
    app.func.req('Addresses/create', {
      province_code: province_code,
      city_code: city_code,
      area_code: area_code,
      addr: addr,
      receiver_name: receiver_name,
      receiver_mobile: receiver_mobile
    }, 'POST', function (res) {
      console.log(res)
      var isError = false;
      var errorMsg;
      if (res.msg == 'addresses.addr.blank') {
        isError = true;
        errorMsg = '地址不能为空';
      } else if (res.msg == 'addresses.receiver_name.blank') {
        isError = true;
        errorMsg = '收货人不能为空';
      } else if (res.msg == 'addresses.receiver_mobile.blank') {
        isError = true;
        errorMsg = '手机号必填';
      } else if (res.msg == 'addresses.receiver_mobile.eleven.number') {
        isError = true;
        errorMsg = '手机格式错误';
      }

      if (isError) {
        wx.showToast({
          title: errorMsg,
          image: '/images/fail.png',
          duration: 2000
        });

        return;
      }

      if (res.code == "success") {
        that.getAddrs();
        that.setData({
          addrId: res.result,
          showAddrDialog: false
        })
        wx.setStorage({
          key: 'addrId',
          data: res.result
        })
        wx.showToast({
          title: '创建成功！',
          icon: 'success',
          duration: 2000
        });
      } else {
        wx.showToast({
          title: '创建地址失败',
          image: '/images/fail.png',
          duration: 2000
        });
      }
    }, {
        'token': wx.getStorageSync('token')
      })
  },
  delAddr: function () {
    var that = this;
    console.log(that.data.addrEdit.id)
    app.func.req('Addresses/delete', {
      id: that.data.addrEdit.id
    }, 'GET', function (res) {
      if (res.code == "success") {
        wx.showToast({
          title: '收货地址已删除！',
          icon: 'success',
          duration: 2000
        });
        app.func.req('Addresses/index', {}, 'GET', function (res) {
          that.setData({
            addrs: res.result,
            showAddrEditDialog: false
          })
          if (res.result.length > 0) {
            if (that.data.addrEdit.id == that.data.curAddr.id) {
              that.setData({
                addrId: res.result[0].id,
                curAddr: res.result[0]
              })
              wx.setStorage({
                key: 'addrId',
                data: res.result[0].id
              })
            }
          }
          else {
            that.setData({
              addrId: null,
              curAddr: null
            })
            wx.removeStorage({ key: 'addrId' });
          }
        }, {
            'token': wx.getStorageSync('token')
          })
      }
    }, {
        'token': wx.getStorageSync('token')
      })
  },
  updateAddr: function (e) {
    var that = this;
    var province_code = that.data.provinces[e.detail.value.province].code;
    var city_code = that.data.cities[e.detail.value.city].code;
    var area_code = that.data.areas[e.detail.value.area].code;
    var addr = e.detail.value.detail;
    var receiver_name = e.detail.value.name;
    var receiver_mobile = e.detail.value.phone;
    console.log(city_code);
    app.func.req('Addresses/update', {
      id: that.data.addrEdit.id,
      province_code: province_code,
      city_code: city_code,
      area_code: area_code,
      addr: addr,
      receiver_name: receiver_name,
      receiver_mobile: receiver_mobile
    }, 'POST', function (res) {
      if (res.code == "success") {
        that.getAddrs();
        that.setData({
          showAddrEditDialog: false,
          showAddrsDialog: true
        })
        wx.showToast({
          title: '收货地址已修改！',
          icon: 'success',
          duration: 2000
        });
      }
    }, {
        'token': wx.getStorageSync('token')
      })
  },
  chooseAddr: function () {
    this.setData({
      showAddrsDialog: true
    })
  },
  addrEdit: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var code1 = that.data.addrs[index].province_code;
    var code2 = that.data.addrs[index].city_code;
    var code3 = that.data.addrs[index].area_code;
    this.getArea(code1, code2, code3);
    this.setData({
      showAddrEditDialog: true,
      addrEdit: that.data.addrs[index],
      showAddrsDialog: false
    })
  },
  addrDelete: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    // var areaId = that.data.addrs[index].id;
    // console.log(areaId); return false;
    this.setData({
      addrEdit: that.data.addrs[index],
    })
    this.delAddr();
  },
  createOrder: function (e) {
    if (!wx.canIUse('button.open-type.getUserInfo')) {
      wx.showModal({
        title: '提示',
        content: '请升级手机微信版本6.5.10及以上',
        showCancel: false
      })
      return;
    }
    var that = this;
    var delivery_amount = that.data.hasDelivery ? that.data.shop.delivery_amount : 0;
    var delivery_free = that.data.isDeliveryFree ? that.data.shop.delivery_free : 0; 
    if (that.data.addrId == null || that.data.addrId == '') {
      wx.showToast({
        title: '收货地址不能为空',
        image: '/images/fail.png',
        duration: 2000
      });
    } else {
      wx.showLoading({ title: '订单创建中...', mask: true });

      app.func.req('orders/create', {
        shop_id: currentShopId,
        address_id: that.data.addrId,
        delivery_amount: delivery_amount,
        delivery_types: that.data.shop.delivery_types,
        products: that.data.products,
        form_id: e.detail.formId,
        remark: that.data.remark,
        threshold: that.data.shop.threshold,
        threshold_rebate: that.data.isthreshold ? that.data.shop.threshold_rebate : 0,
        delivery_free: delivery_free
      }, 'POST', function (res) {
        wx.hideLoading();
        if (res.code == 'error') {
          var title = '订单提交失败';
            if(res.msg == 'status'){
              title = '商品已下架'
            }
          if (res.msg == 'cart.products.limit') {
            title = '商品超过限购';
          }
          if (res.msg == 'product.num.error') {
            title = '库存不足';
          }
          wx.showToast({
            title: title,
            image: '/images/fail.png',
            duration: 2000
          });
          return false
        }
        if (res.code == "success") {
          wx.showToast({
            title: '订单提交成功！！',
            icon: 'success',
            duration: 2000
          });
          if (!that.data.is_express) {
            var carts = wx.getStorageSync('carts');
            for (var i = 0; i < carts.length; i++) {
              if (carts[i].shopId == currentShopId) {
                carts.splice(i, 1)
              }
            }
            wx.setStorage({
              key: 'carts',
              data: carts
            })
          }

          //支付
          var orderId = res.result;
          app.func.req('orders/show', {
            id: orderId
          }, 'GET', function (res) {
            var order = res.result;

            app.func.req('pay/xcx', {
              tran_no: order['tran_no']
            }, 'POST', function (res) {
              var prepay_id = res.result['prepay_id'];
              wx.requestPayment({
                'timeStamp': res.result['timestamp'] + '',
                'nonceStr': res.result['nonce_str'],
                'package': 'prepay_id=' + prepay_id,
                'signType': 'MD5',
                'paySign': res.result['pay_sign'],
                'success': function (res) {
                  app.func.req('orders/prepay_id', {
                    tran_no: order['tran_no'],
                    prepay_id: prepay_id
                  }, 'POST', function (res) {
                    console.log(res);
                    wx.showToast({
                      title: '支付成功',
                      icon: 'success',
                      duration: 2000,
                      success: function () {
                        wx.redirectTo({
                          url: '/pages/orders/success?id=' + order['id']
                        });
                      }
                    })
                  }, {
                      'token': wx.getStorageSync('token')
                    });
                },
                'fail': function (res) {
                  wx.showToast({
                    title: '支付失败',
                    image: '/images/fail.png',
                    duration: 2000,
                    success: function () {
                      wx.redirectTo({
                        url: '/pages/orders/order?id=' + order['id']
                      });
                    }
                  });
                }
              });
            }, {
                'token': wx.getStorageSync('token')
              })
          }, {
              'token': wx.getStorageSync('token')
            })

        }
      }, {
          'token': wx.getStorageSync('token')
        });
    }
  },

  getWechatAddr: function () {
    var that = this;
    wx.chooseAddress({
      success: function (response) {
        console.log(response.telNumber);
        app.func.req('Addresses/create', {
          province_name: response.provinceName,
          city_name: response.cityName,
          area_name: response.countyName,
          addr: response.detailInfo,
          receiver_name: response.userName,
          receiver_mobile: response.telNumber,
          is_wechat_addr: 1
        }, 'POST', function (res) {
          var isError = false;
          var errorMsg;
          if (res.msg == 'addresses.addr.blank') {
            isError = true;
            errorMsg = '地址不能为空';
          } else if (res.msg == 'addresses.receiver_name.blank') {
            isError = true;
            errorMsg = '收货人不能为空';
          } else if (res.msg == 'addresses.receiver_mobile.blank') {
            isError = true;
            errorMsg = '电话必填';
          }

          if (isError) {
            wx.showToast({
              title: errorMsg,
              image: '/images/fail.png',
              duration: 2000
            });

            return;
          }

          if (res.code == "success") {
            that.getAddrs();
            that.setData({
              addrId: res.result,
              showAddrDialog: false
            })
            wx.setStorage({
              key: 'addrId',
              data: res.result
            })
            wx.showToast({
              title: '创建成功！',
              icon: 'success',
              duration: 2000
            });
          } else {
            wx.showToast({
              title: '创建地址失败',
              image: '/images/fail.png',
              duration: 2000
            });
          }
        }, {
            'token': wx.getStorageSync('token')
          })
      }
    });
    return false;

  },
  setRemark: function(e) {
    this.setData({
      remark: e.detail.value
    })
  },
  updateUserInfo: function(e) {
    if (e.detail.errMsg == 'getUserInfo:ok') {
      app.util.userAuth(app, e.detail, function (res) { });
    }
  }
})
